<template>
    <div class="edit-user-info-container">
        <h2>修改个人信息</h2>
        <form @submit.prevent="updateUserInfo">
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" id="username" v-model="userInfo.username" required />
            </div>
            <div class="form-group">
                <label for="email">邮箱（不可修改）</label>
                <input type="email" id="email" v-model="userInfo.email" readonly />
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" v-model="userInfo.password" required />
            </div>
            <button type="submit">保存更改</button>
        </form>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import { post } from '../until/request';
import Swal from 'sweetalert2';

const userInfo = ref({
    username: '',
    email: '',
    password: ''
});

// 从本地存储或API加载用户信息
const storedData = localStorage.getItem('login');
if (storedData) {
    Object.assign(userInfo.value, JSON.parse(storedData));
}

// 更新用户信息
async function updateUserInfo() {
    try {
        const response = await post('/user/updateUser', userInfo.value);
        if (response && response.code === 1) {
            console.log("用户信息已更新:", response.data);
            // 更新本地存储
            localStorage.setItem('login', JSON.stringify(userInfo.value));
            Swal.fire({
                icon: 'success',
                title: '用户信息更新成功',
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: '用户信息更新失败',
            });
        }
    } catch (error) {
        console.error("更新用户信息时出错:", error);
        Swal.fire({
            icon: 'error',
            title: '更新用户信息时出错',
        });
    }
}
</script>

<style scoped>
.edit-user-info-container {
    max-width: 600px;
    margin: 2rem auto;
    padding: 2rem;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.form-group {
    margin-bottom: 1.5rem;
}

label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: bold;
}

input {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid #ccc;
    border-radius: 4px;
}

button {
    background-color: #007bff;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}
</style>